package pwd.allen.config;

import com.google.common.collect.Lists;
import org.apache.dubbo.config.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import pwd.allen.service.IHelloService;
import pwd.allen.service.impl.HelloServiceImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * 使用注解API的方式配置dubbo
 * 需要开启dubbo包扫描，引入dubbo-spring-boot-starter后默认会开启，除非设置dubbo.enabled=false
 *
 * 问题：
 * 	1）如果设置了-Ddubbo.protocol.port=20881，端口会被覆盖，jvm-D参数优先级最高
 */
//@Configuration
public class MyDubboConfig {

	/**
	 * 配置dubbo application
	 * @return
	 */
	@Bean
	public ApplicationConfig applicationConfig() {
		ApplicationConfig applicationConfig = new ApplicationConfig();
		applicationConfig.setName("boot-api-service-provider");
		return applicationConfig;
	}

	/**
	 * 配置dubbo registry
	 * <dubbo:registry protocol="nacos" address="127.0.0.1:8848"></dubbo:registry>
	 */
	@Bean
	public RegistryConfig registryConfig() {
		RegistryConfig registryConfig = new RegistryConfig();
		registryConfig.setProtocol("nacos");
		registryConfig.setAddress("127.0.0.1:8848");
		return registryConfig;
	}

	/**
	 * <dubbo:protocol name="dubbo" port="20882"></dubbo:protocol>
	 *
	 * @return
	 */
	@Bean
	public ProtocolConfig protocolConfig() {
		ProtocolConfig protocolConfig = new ProtocolConfig();
		protocolConfig.setName("dubbo");
		protocolConfig.setPort(20883);
		return protocolConfig;
	}

	/**
	 * <dubbo:service interface="pwd.allen.service.IHelloService" ref="helloService" version="pwd-1.0">
	 *         <dubbo:method name="sayHello" timeout="1000"/>
	 *     </dubbo:service>
	 * @param service
	 * @return
	 */
	@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
	@Bean
	public ServiceConfig<IHelloService> userServiceConfig(IHelloService service){
		ServiceConfig<IHelloService> serviceConfig = new ServiceConfig<IHelloService>();
		serviceConfig.setInterface(IHelloService.class);
		serviceConfig.setRef(service);
		serviceConfig.setVersion("pwd-1.0");

		//配置每一个method的信息
		MethodConfig methodConfig = new MethodConfig();
		methodConfig.setName("sayHello");
		methodConfig.setTimeout(1000);

		//将method的设置关联到service配置中
//		List<MethodConfig> methods = new ArrayList<>();
//		methods.add(methodConfig);
//		serviceConfig.setMethods(Lists.newArrayList(methodConfig));
		
		//ProviderConfig
		//MonitorConfig
		
		return serviceConfig;
	}
	@Bean
	public IHelloService helloService() {
		return new HelloServiceImpl();
	}

}
